<script setup lang="ts">
import type { FormInstance } from 'element-plus';
import { reactive, ref, toRaw } from 'vue';
import { useUserStore } from '@vben/stores';
import { getEmailCodeApi } from '#/api';
import { EmailMatcher, idCardRegex } from '#/utils/constants';
import Code from '#/components/common/code.vue';
import { $t } from '@vben/locales';


defineOptions({ name: 'RealNameAuth' });
const ruleFormRef = ref<FormInstance>();
const userStore = useUserStore();
const rules = {
  nameCn: [{ required: true, message: $t('realNameAuth.validation.nameRequired'), trigger: 'blur' }],
  idCard: [
    {
      required: true,
      pattern: idCardRegex,
      message: $t('realNameAuth.validation.idCardRequired'),
      trigger: 'blur',
    },
  ],
  email: [
    {
      required: true,
      pattern: EmailMatcher,
      message: $t('realNameAuth.validation.emailRequired'),
      trigger: 'blur',
    },
  ],
  emailCode: [{ required: true, message: $t('realNameAuth.validation.emailCodeRequired'), trigger: 'blur' }],
};

const ruleForm = reactive({
  nameCn: '',
  idCard: '',
  email: '',
  emailCode: '',
});

// 获取验证码
const getCode = (callback: Function) => {
  ruleFormRef.value?.validateField(['email'], (valid) => {
    if (valid) {
      callback()
      getEmailCodeApi({ email: ruleForm.email });
    }
  });
};

const getData = async () => {
  const data = await ruleFormRef.value
    ?.validate(async (valid: boolean) => { })
    .then((res) => {
      return res ? toRaw(ruleForm) : res;
    });
  return data;
};

defineExpose({
  getData,
});
</script>
<template>
  <div class="real-name-auth">
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
      <el-form-item :label="$t('realNameAuth.phone')" prop="phone">
        {{ userStore.userInfo?.phone }}
      </el-form-item>
      <el-form-item :label="$t('realNameAuth.name')" prop="nameCn">
        <el-input v-model="ruleForm.nameCn" minlength="1" maxlength="30" :placeholder="$t('realNameAuth.namePhTxt')" />
      </el-form-item>
      <el-form-item :label="$t('realNameAuth.idCard')" prop="idCard">
        <el-input v-model="ruleForm.idCard" maxlength="18" :placeholder="$t('realNameAuth.idCardPhTxt')" />
      </el-form-item>
      <el-form-item :label="$t('realNameAuth.email')" prop="email">
        <el-input v-model="ruleForm.email" maxlength="255" :placeholder="$t('realNameAuth.emailPhTxt')" />
      </el-form-item>
      <el-form-item :label="$t('realNameAuth.emailVerification')" prop="emailCode">
        <el-input v-model="ruleForm.emailCode" minlength="3" maxlength="10"
          :placeholder="$t('realNameAuth.verificationCodePhTxt')">
          <template #append>
            <Code @get-code="getCode" :codeName="$t('realNameAuth.emailCode')" :authCode="ruleForm.email" />
          </template>
        </el-input>
      </el-form-item>
    </el-form>
  </div>
</template>
<style></style>
